<template>
  <div>
    <div class="mb-8">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-3xl font-bold text-gray-800 mb-2">主控制台</h1>
          <p class="text-gray-600">欢迎回来，{{ authStore.userInfo?.name || '张管理员' }}。今日是 {{ currentDate }}</p>
        </div>
      </div>
    </div>

    <div class="bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl p-6 mb-8 text-white">
      <div class="flex items-center justify-between">
        <div>
          <h2 class="text-xl font-semibold mb-2">系统实时状态</h2>
          <p class="text-blue-100">所有系统运行正常，数据同步正常</p>
        </div>
        <div class="flex items-center space-x-6">
          <div class="text-center">
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center mb-2">
              <i class="fas fa-server text-xl"></i>
            </div>
            <div class="text-sm text-blue-100">系统状态</div>
            <div class="text-lg font-bold">{{ dashboardStore.systemStatus.status === 'normal' ? '正常' : '异常' }}</div>
          </div>
          <div class="text-center">
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center mb-2">
              <i class="fas fa-clock text-xl"></i>
            </div>
            <div class="text-sm text-blue-100">最后更新</div>
            <div class="text-lg font-bold">{{ dashboardStore.systemStatus.lastUpdate }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white p-6 rounded-2xl shadow-lg card-hover border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-500 text-sm font-medium">管道线路</p>
            <p class="text-3xl font-bold text-gray-800 mt-2">{{ dashboardStore.statistics.totalLines }}</p>
            <div class="flex items-center mt-2">
              <span class="text-green-600 text-sm font-semibold">↑ 8.20%</span>
              <span class="text-gray-500 text-sm ml-2">较上月</span>
            </div>
          </div>
          <div class="w-16 h-16 bg-blue-500 rounded-2xl flex items-center justify-center">
            <i class="fas fa-route text-white text-2xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white p-6 rounded-2xl shadow-lg card-hover border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-500 text-sm font-medium">今日巡检</p>
            <p class="text-3xl font-bold text-gray-800 mt-2">{{ dashboardStore.statistics.todayInspections }}</p>
            <div class="flex items-center mt-2">
              <span class="text-green-600 text-sm font-semibold">↑ 12.50%</span>
              <span class="text-gray-500 text-sm ml-2">较昨日</span>
            </div>
          </div>
          <div class="w-16 h-16 bg-green-500 rounded-2xl flex items-center justify-center">
            <i class="fas fa-clipboard-check text-white text-2xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white p-6 rounded-2xl shadow-lg card-hover border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-500 text-sm font-medium">待处理缺陷</p>
            <p class="text-3xl font-bold text-gray-800 mt-2">{{ dashboardStore.statistics.pendingDefects }}</p>
            <div class="flex items-center mt-2">
              <span class="text-red-600 text-sm font-semibold">↑ 3</span>
              <span class="text-gray-500 text-sm ml-2">新增</span>
            </div>
          </div>
          <div class="w-16 h-16 bg-red-500 rounded-2xl flex items-center justify-center">
            <i class="fas fa-exclamation-triangle text-white text-2xl"></i>
          </div>
        </div>
      </div>

      <div class="bg-white p-6 rounded-2xl shadow-lg card-hover border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-500 text-sm font-medium">完成率</p>
            <p class="text-3xl font-bold text-gray-800 mt-2">{{ dashboardStore.statistics.completionRate.toFixed(2) }}%</p>
            <div class="flex items-center mt-2">
              <span class="text-green-600 text-sm font-semibold">↑ 2.10%</span>
              <span class="text-gray-500 text-sm ml-2">较上月</span>
            </div>
          </div>
          <div class="w-16 h-16 bg-purple-500 rounded-2xl flex items-center justify-center">
            <i class="fas fa-percentage text-white text-2xl"></i>
          </div>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <div class="bg-white p-6 rounded-lg shadow">
        <h3 class="text-lg font-semibold mb-4">本月巡检进度</h3>
        <canvas id="inspectionChart" height="200"></canvas>
      </div>
      <div class="bg-white p-6 rounded-lg shadow">
        <h3 class="text-lg font-semibold mb-4">缺陷等级分布</h3>
        <canvas id="defectChart" height="200"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { Chart, LineElement, PointElement, LineController, CategoryScale, LinearScale, DoughnutController, ArcElement, Tooltip, Legend, Filler } from 'chart.js'
import { useDashboardStore } from '@/stores/dashboard'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

Chart.register(LineElement, PointElement, LineController, CategoryScale, LinearScale, DoughnutController, ArcElement, Tooltip, Legend, Filler)

const dashboardStore = useDashboardStore()
const authStore = useAuthStore()
const loading = ref(false)

/**
 * 获取当前日期
 */
const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[now.getDay()]
  
  return `${year}年${month}月${day}日，${weekday}`
})

/**
 * 初始化图表
 */
const initCharts = () => {
  // 巡检进度图表
  const ctx1 = document.getElementById('inspectionChart')
  if (ctx1 && Chart) {
    // 销毁已存在的图表实例
    if (ctx1._chart) {
      ctx1._chart.destroy()
    }
    
    new Chart(ctx1, {
      type: 'line',
      data: {
        labels: dashboardStore.inspectionProgress.labels,
        datasets: [{
          label: '巡检完成数',
          data: dashboardStore.inspectionProgress.data,
          borderColor: 'rgb(59, 130, 246)',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          tension: 0.4,
          fill: true
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false }
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          },
          x: {
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          }
        }
      }
    })
  }

  // 缺陷分布图表
  const ctx2 = document.getElementById('defectChart')
  if (ctx2 && Chart) {
    // 销毁已存在的图表实例
    if (ctx2._chart) {
      ctx2._chart.destroy()
    }
    
    new Chart(ctx2, {
      type: 'doughnut',
      data: {
        labels: dashboardStore.defectDistribution.labels,
        datasets: [{
          data: dashboardStore.defectDistribution.data,
          backgroundColor: dashboardStore.defectDistribution.colors,
          borderWidth: 0
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              padding: 20,
              usePointStyle: true
            }
          }
        }
      }
    })
  }
}

/**
 * 刷新数据
 */
const refreshData = async () => {
  loading.value = true
  try {
    await dashboardStore.refreshAllData()
    // 重新初始化图表
    setTimeout(() => {
      initCharts()
    }, 100)
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}


onMounted(async () => {
  try {
    // 加载数据
    await dashboardStore.refreshAllData()
    // 初始化图表
    setTimeout(() => {
      initCharts()
    }, 100)
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.card { background: #fff; border: 1px solid #eee; padding: 16px; border-radius: 6px; }

/* 图表容器样式 */
canvas {
  height: 200px !important;
  width: 100% !important;
}

/* 确保图表容器有固定高度 */
.bg-white {
  position: relative;
  min-height: 200px;
}

.bg-white canvas {
  position: relative;
  z-index: 1;
}
</style>
